package com.step.ems.pages.wb

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.king.ultraswiperefresh.NestedScrollMode
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.indicator.classic.ClassicRefreshHeader
import com.step.ems.R
import com.step.ems.api.WbStatus
import com.step.ems.api.res.WbRes
import com.step.ems.common.RefreshType
import com.step.ems.common.UiState
import com.step.ems.component.EndlessLazyColumn
import com.step.ems.component.MySearchBar
import com.step.ems.component.MyTopBar
import com.step.ems.component.PageStatus
import com.step.ems.ui.theme.ContentBg

@Composable
fun WbPageScreen(
    onItemClick: (WbRes) -> Unit,
    viewModel: WbPageViewModel = hiltViewModel(),
) {
    Scaffold(topBar = {
        MyTopBar(stringResource(R.string.wb))
    }) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .background(color = ContentBg)
        ) {
            Spacer(modifier = Modifier.height(1.dp))
            Row(
                modifier = Modifier
                    .background(Color.White)
                    .height(55.dp)
                    .padding(horizontal = 16.dp, vertical = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                MySearchBar(
                    modifier = Modifier.weight(1f),
                    value = viewModel.filter,
                    onValueChange = { viewModel.filter = it },
                    onSearch = { viewModel.getData(RefreshType.Pull) }
                )
                Spacer(modifier = Modifier.width(8.dp))
                WbStatusDropdown(
                    Modifier.width(stringResource(id = R.string.wbTypeBtnWidth).toInt().dp),
                    viewModel
                )
            }
            Spacer(modifier = Modifier.height(4.dp))

            val data by viewModel.data.collectAsStateWithLifecycle()
            val uiState by viewModel.uiState.collectAsStateWithLifecycle()
            PageStatus(uiState = uiState, total = data.size, retry = { viewModel.getData(RefreshType.Init) }) {
                WbList(data = data, uiState = uiState, viewModel = viewModel, onItemClick = onItemClick)
            }
        }
    }
}

@Composable
fun WbList(
    data: List<WbRes>,
    uiState: UiState,
    onItemClick: (WbRes) -> Unit,
    viewModel: WbPageViewModel,
) {
    val pullRefreshState = viewModel.pullRefreshState

    UltraSwipeRefresh(
        state = pullRefreshState,
        loadMoreEnabled = false,
        vibrateEnabled = true,
        onRefresh = {
            viewModel.getData(RefreshType.Pull)
        },
        onLoadMore = {},
        headerScrollMode = NestedScrollMode.Translate,
        headerIndicator = {
            ClassicRefreshHeader(it)
        },
    ) {
        EndlessLazyColumn(
            modifier = Modifier.fillMaxSize(),
            uiState = uiState,
            items = data,
            itemKey = { item -> item.id },
            loadMore = { viewModel.getData(RefreshType.LoadMore) }
        ) { item ->
            WbItem(item, onItemClick)
            Spacer(modifier = Modifier.height(4.dp))
        }
    }
}

@Composable
fun WbItem(
    item: WbRes,
    onItemClick: (WbRes) -> Unit,
) {
    Box(modifier = Modifier
        .clickable { onItemClick(item) }
        .background(Color.White)
        .padding(horizontal = 16.dp, vertical = 12.dp)) {
        Column {
            WbItemLine(stringResource(R.string.maintenanceNo), item.maintenanceNo)
            WbItemLine(stringResource(R.string.maintenanceDate), "2024-01-01")
            WbItemLine(stringResource(R.string.elevatorName), item.elevatorName)
            WbItemLine(stringResource(R.string.wbWorker1), item.maintainerOneName)
            WbItemLine(stringResource(R.string.wbWorker2), item.maintainerTwoName)
        }
        val wbStatus = WbStatus.getItem(item.maintenanceStatus)
        Text(
            stringResource(id = wbStatus?.titleResId ?: R.string.none), color = wbStatus?.color ?: Color.Black,
            modifier = Modifier
                .align(Alignment.CenterEnd)
                .offset(x = (-10).dp)
                .background(Color.White),
        )
        Icon(
            Icons.AutoMirrored.Rounded.KeyboardArrowRight,
            contentDescription = ">",
            tint = Color.LightGray,
            modifier = Modifier.align(Alignment.CenterEnd).offset(x = 12.dp)
        )
    }
}

@Composable
fun WbItemLine(title: String, value: String?) {
    Row(modifier = Modifier.fillMaxWidth()) {
        Text(text = "$title：", fontSize = 16.sp)
        Text(text = value ?: "-", fontSize = 16.sp)
    }
}

@Composable
fun WbStatusDropdown(modifier: Modifier = Modifier, viewModel: WbPageViewModel) {
    var expanded by remember { mutableStateOf(false) }
    val items = WbStatus.entries.toTypedArray()
    Box(
        modifier = modifier
    ) {
        Button(
            modifier = Modifier.fillMaxSize(),
            shape = RoundedCornerShape(4.dp),
            contentPadding = PaddingValues(horizontal = 5.dp),
            onClick = { expanded = true }
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    text = stringResource(id = items[viewModel.wbStatusIndex].titleResId),
                    modifier = Modifier.weight(1f),
                    fontSize = 14.sp,
                    color = Color.White,
                    textAlign = TextAlign.Center,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Icon(
                    Icons.Filled.KeyboardArrowDown,
                    contentDescription = "^"
                )
            }
        }
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier.background(Color.White)
        ) {
            items.forEachIndexed { index, item ->
                DropdownMenuItem(
                    text = { Text(stringResource(id = item.titleResId)) },
                    onClick = {
                        viewModel.wbStatusIndex = index
                        expanded = false
                        viewModel.getData(RefreshType.Pull)
                    }
                )
            }
        }
    }
}